package com.heima.behavior.service.impl;
import java.util.Date;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApUnlikeBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

@Service
public class ApUnlikeBehaviorServiceImpl implements ApUnlikeBehaviorService {

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ResponseResult unlikeBehavior(UnLikesBehaviorDto dto) {
        //1.检查参数  参数和登陆状态
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.获取不喜欢的行为信息，判断是否已经点过不喜欢，已经点过不喜欢，取消掉不喜欢
        //获取用户行为实体类
        ApBehaviorEntry byUserIdOrEquipmentId = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (byUserIdOrEquipmentId==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"获取行为实体信息失败");
        }
        Query query = Query.query(Criteria.where("entryId").is(byUserIdOrEquipmentId.getId()).and("articleId").is(dto.getArticleId()));
        ApUnlikesBehavior unlikesBehavior = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
        if (dto.getType()==0&&unlikesBehavior!=null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"您已经设置过不喜欢");
        }
        if (dto.getType().intValue() == 0) {
            unlikesBehavior = new ApUnlikesBehavior();
            unlikesBehavior.setEntryId(byUserIdOrEquipmentId.getId());
            unlikesBehavior.setArticleId(dto.getArticleId());
            unlikesBehavior.setType((short) 0);
            unlikesBehavior.setCreatedTime(new Date());
            mongoTemplate.save(unlikesBehavior);
        } else {
            mongoTemplate.remove(query,ApUnlikesBehavior.class);
        }

        return ResponseResult.okResult();
    }
}
